package com.shengdong.water.code.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.shengdong.water.R

class EmptyRecyclerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {

    private var emptyView: View? = null
    private var emptyMessage: String? = null
//    private var retryCallback: (() -> Unit)? = null

    // 观察者用于监听适配器数据变化
    private val observer = object : AdapterDataObserver() {
        override fun onChanged() {
            checkIfEmpty()
        }

        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            checkIfEmpty()
        }

        override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
            checkIfEmpty()
        }
    }

    /**
     * 设置空视图
     */
    fun setEmptyView(emptyView: View) {
        this.emptyView = emptyView
        checkIfEmpty()
    }

    /**
     * 设置空状态消息
     */
    fun setEmptyMessage(message: String) {
        this.emptyMessage = message
        emptyView?.findViewById<android.widget.TextView>(R.id.tv_empty)?.text =
            message
    }


    override fun setAdapter(adapter: Adapter<*>?) {
        val oldAdapter = getAdapter()
        oldAdapter?.unregisterAdapterDataObserver(observer)

        super.setAdapter(adapter)

        adapter?.registerAdapterDataObserver(observer)
        checkIfEmpty()
    }

    /**
     * 检查列表是否为空，并相应地显示或隐藏空视图
     */
    private fun checkIfEmpty() {
        val isEmpty = adapter == null || adapter?.itemCount == 0
        emptyView?.visibility = if (isEmpty) View.VISIBLE else View.GONE
        visibility = if (isEmpty) View.GONE else View.VISIBLE
    }
}